<template>
	<ge-page id="ge-page" :vanNavBarObj="vanNavBarObj">
		<view class="form-list">
			<view class="cont-one">
				<view class="form-label">商品名称</view>
				<view class="form-content">
					<input type="text" v-model="goodsInfo.goods_name" class="common-input" placeholder="请输入" />
				</view>

				<view class="form-label">商品图片</view>
				<view class="form-content">
					<uni-file-picker v-model="goodsInfo.goods_images"  @select='selectUpload' fileMediatype="image" mode="grid"
						@delete="onRemoveUpload" :image-styles="uploadListSty" />
				</view>

				<view class="form-label">商品分类</view>
				<view class="form-content">
					<uni-data-checkbox multiple v-model="goodsInfo.categoryIds" :localdata="category"></uni-data-checkbox>
				</view>

				<!-- <view class="form-label">商品编码</view>
				<view class="form-content">
					<input type="text" v-model="goodsInfo.goods_no" class="common-input" placeholder="请输入" />
				</view>、

				<view class="form-label">运费模板</view>
				<view class="form-content">
					<uni-data-checkbox v-model="goodsInfo.delivery_id" :localdata="deliveryList"></uni-data-checkbox>
				</view> -->

				<view class="form-label">商品状态</view>
				<view class="form-content">
					<uni-data-checkbox v-model="goodsInfo.status" :localdata="status"></uni-data-checkbox>
				</view>

				<view class="form-label">商品排序</view>
				<view class="form-content">
					<input type="number" v-model="goodsInfo.sort" class="common-input" placeholder="请输入" />
				</view>
			</view>



			<view class="cont-one">
				<view class="form-label">规格类型</view>
				<view class="form-content">
					<uni-data-checkbox v-model="goodsInfo.spec_type" :localdata="specType"></uni-data-checkbox>
				</view>
				<template v-if="goodsInfo.spec_type === 10">
					<view class="form-label">商品价格</view>
					<view class="form-content">
						<input type="number"  maxlength="10" v-model="goodsInfo.goods_price" class="common-input" placeholder="请输入" />元
					</view>
					<view class="form-label">划线价</view>
					<view class="form-content">
						<input type="number"   maxlength="10" v-model="goodsInfo.line_price" class="common-input" placeholder="请输入" />元
					</view>
					<view class="form-label">当前库存数量</view>
					<view class="form-content">
						<input type="number"  maxlength="10" v-model="goodsInfo.stock_num" class="common-input" placeholder="请输入" @input="handleInput" />件
					</view>
					<!-- <view class="form-label">商品重量</view>
					<view class="form-content">
						<input type="text" v-model="goodsInfo.goods_weight" class="common-input" placeholder="请输入" />千克
						(Kg)
					</view> -->
					<view class="form-label">库存计算方式</view>
					<view class="form-content">
						<uni-data-checkbox v-model="goodsInfo.deduct_stock_type" :localdata="deductStockType"></uni-data-checkbox>
					</view>
					<view class="form-label">商品限购</view>
					<view class="form-content">
						<uni-data-checkbox v-model="goodsInfo.is_restrict" :localdata="isRestrict"></uni-data-checkbox>
					</view>
					<template v-if="goodsInfo.is_restrict === 1">
						<view class="form-label">总限购</view>
						<view class="form-content">
							<input type="number" v-model="goodsInfo.restrict_total" class="common-input" placeholder="请输入" />件/人
						</view>
						<view class="form-label">每单限购</view>
						<view class="form-content">
							<input type="number" v-model="goodsInfo.restrict_single" class="common-input" placeholder="请输入" />222件/人
						</view>
					</template>
				</template>
				<template v-if="goodsInfo.spec_type === 20">
					<view class="form-label">商品规格</view>
					<view class="form-content">
						<view class="add-btn" v-if="goodsInfo.specList.length < 3" @click="onAddSpecList">添加</view>
						<text>最多添加3个商品规格组，生成的SKU数量不能超出50个</text>
					</view>

					<view v-for="(item,index) in goodsInfo.specList" :key="index" class="specList">
						<view class="sku-name">
							<view class="form-label">规格组名字</view>
							<view class="form-content">
								<input type="text" v-model="item.spec_name" class="common-input" placeholder="请输入"
									@change="renderSkuList()" />
								<van-icon @click="onRemoveSpecList(index)" class="delete-icon" name="delete" color="#1b9d35"
									size="20" />
							</view>
						</view>
						<view class="valueList">
							<view class="form-content">
								<view class="add-btn" @click="onAddValueList(index)">添加规格值</view>
							</view>
							<view v-for="(vItem,vIndex) in item.valueList" :key="vIndex">
								<view class="form-content">
									<input type="text" v-model="vItem.spec_value" class="common-input" placeholder="请输入"
										@change="renderSkuList()" />
									<van-icon @click="onRemoveValueList(index,vIndex)" class="delete-icon" name="delete" color="#1b9d35"
										size="20" />
								</view>
							</view>
						</view>
					</view>

					<view class="cont-one sku-list">
						<view class="form-label">SKU</view>
						<view class="sku-items" v-for="(cartesian,index) in cartesianList" :key="index">
							<view class="form-label">
								<text class="" v-for="(cItem,cIndex) in cartesian.list" :key="cIndex">
									{{cItem.spec_value}}
								</text>
							</view>
							<view class="form-items">
								<view>
									<view class="form-label">预览图</view>
									<view class="form-content">
										<uni-file-picker v-model="cartesian.image" :limit="1" @select='(e)=>selectSKUUpload(e,index)'
											fileMediatype="image" mode="grid" @delete="(e)=>onRemoveSKUUpload(e,index)"
											:image-styles="uploadListSty" />
									</view>
								</view>
								<view>
									<view class="form-label">商品价格</view>
									<view class="form-content">
										<input type="number" v-model="cartesian.goods_price" class="common-input" placeholder="请输入" />
									</view>
								</view>
							</view>
							<view class="form-items">
								<view>
									<view class="form-label">划线价格</view>
									<view class="form-content">
										<input type="number" v-model="cartesian.line_price" class="common-input" placeholder="请输入" />
									</view>
								</view>
								<view>
									<view class="form-label">库存数量</view>
									<view class="form-content">
										<input type="number" v-model="cartesian.stock_num" class="common-input" placeholder="请输入" />
									</view>
								</view>
							</view>
							<view class="form-items">
								<!-- <view>
									<view class="form-label">商品重量 (KG)</view>
									<view class="form-content">
										<input type="text" v-model="cartesian.goods_weight" class="common-input" placeholder="请输入" />
									</view>
								</view> -->
								<view>
									<view class="form-label">SKU编码</view>
									<view class="form-content">
										<input type="text" v-model="cartesian.goods_sku_no" class="common-input" placeholder="请输入" />
									</view>
								</view>
							</view>
						</view>
					</view>

				</template>

				<template v-if="goodsInfo.spec_type === 20">
					<view class="form-label">库存计算方式</view>
					<view class="form-content">
						<uni-data-checkbox v-model="goodsInfo.deduct_stock_type" :localdata="deductStockType"></uni-data-checkbox>
					</view>

					<view class="form-label">商品限购</view>
					<view class="form-content">
						<uni-data-checkbox v-model="goodsInfo.is_restrict" :localdata="isRestrict"></uni-data-checkbox>
					</view>
					<template v-if="goodsInfo.is_restrict === 1">
						<view class="form-label">总限购</view>
						<view class="form-content">
							<input type="number" v-model="goodsInfo.restrict_total" class="common-input" placeholder="请输入" />件/人
						</view>
						<view class="form-label">每单限购</view>
						<view class="form-content">
							<input type="number" v-model="goodsInfo.restrict_single" class="common-input" placeholder="请输入" />件/人
						</view>
					</template>
				</template>
			</view>

			<view class="cont-one">
				<view class="form-label">商品详情</view>
				<view class="form-content">
					<textarea type="text" v-model="goodsInfo.content" class="common-input" placeholder="请输入" />
				</view>
			</view>


			<view class="cont-one">
				<!-- <view class="form-label">更多设置</view> -->
				<!-- <view class="form-label">商品卖点</view>
				<view class="form-content">
					<input type="text" v-model="goodsInfo.selling_point" class="common-input" placeholder="请输入" />
				</view> -->
				<!-- <view class="form-label">服务与承诺</view>
				<view class="form-content">
					<uni-data-checkbox multiple v-model="goodsInfo.serviceIds" :localdata="serviceList"></uni-data-checkbox>
				</view> -->
				<!-- <view class="form-label">初始销量</view>
				<view class="form-content">
					<input type="text" v-model="goodsInfo.sales_initial" class="common-input" placeholder="请输入" />
				</view> -->
			</view>
			<!-- <view class="cont-one">
				<view class="form-label">积分设置</view>
				<view class="form-label">积分赠送</view>
				<view class="form-content">
					<uni-data-checkbox v-model="goodsInfo.is_points_gift" :localdata="isPointsGift"></uni-data-checkbox>
				</view>
				<view class="form-label">积分抵扣</view>
				<view class="form-content">
					<uni-data-checkbox v-model="goodsInfo.is_points_discount" :localdata="isPointsDiscount"></uni-data-checkbox>
				</view>
			</view>

			<view class="cont-one">
				<view class="form-label">会员折扣设置</view>
				<view class="form-label">会员折扣</view>
				<view class="form-content">
					<uni-data-checkbox v-model="goodsInfo.is_enable_grade" :localdata="isEnableGrade"></uni-data-checkbox>
				</view>

				<template v-if="goodsInfo.is_enable_grade==1">
					<view class="form-label">会员折扣设置</view>
					<view class="form-content">
						<uni-data-checkbox v-model="goodsInfo.is_alone_grade" :localdata="isAloneGrade"></uni-data-checkbox>
					</view>
				</template>

				<template v-if="goodsInfo.is_alone_grade==1 && goodsInfo.is_enable_grade==1">
					<view class="form-content" v-for="(item,index) in userGradeList" :key="index">
						<text style="width:210rpx">{{item.name}}</text>
						<input type="text" v-model="goodsInfo.alone_grade_equity[`${item.grade_id}`]" class="common-input"
							placeholder="请输入" />
						<text>折</text>
					</view>
				</template>
			</view> -->

		</view>
		<view class="keep-button" @click="handleKeep">
			保存
		</view>
	</ge-page>
</template>

<script>
	import {
		storageKey,
		appConfig
	} from '@/constant/config';

	/**
	 * 生成笛卡尔积数据
	 * cartesianProductOf([arr1, arr2, arr3 ...])
	 */
	const cartesianProductOf = arrays => {
		if (!arrays.length) {
			return []
		}
		return Array.prototype.reduce.call(arrays, (arr1, arr2) => {
			var ret = []
			arr1.forEach(v1 => {
				arr2.forEach(v2 => {
					ret.push(v1.concat([v2]))
				})
			})
			return ret
		}, [
			[]
		])
	}

	export default {
		props: {

		},
		data() {
			return {
				goods_id: null,
				vanNavBarObj: {
					title: '商品信息',
				},
				formData: {
					proTypeId: null,
				},
				uploadListSty: {
					width: 80,
					height: 80,
					border: {
						color: "#fff",
						width: 2,
						radius: '2px'
					}
				},
				goodsInfo: {},
				category: [],
				status: [{
						text: '上架',
						value: 10
					},
					{
						text: '下架',
						value: 20
					},
				],
				deductStockType: [{
						text: '下单减库存',
						value: 10
					},
					{
						text: '付款减库存',
						value: 20
					},
				],
				specType: [{
						text: '单规格',
						value: 10
					},
					{
						text: '多规格',
						value: 20
					},
				],
				isRestrict: [{
						text: '是',
						value: 1
					},
					{
						text: '否',
						value: 0
					},
				],
				cartesianList: [],
				serviceList: [],
				isPointsGift: [{
						text: '开启',
						value: 1
					},
					{
						text: '关闭',
						value: 0
					},
				],
				isPointsDiscount: [{
						text: '开启',
						value: 1
					},
					{
						text: '关闭',
						value: 0
					},
				],
				isEnableGrade: [{
						text: '开启',
						value: 1
					},
					{
						text: '关闭',
						value: 0
					},
				],
				isAloneGrade: [{
						text: '默认等级折扣',
						value: 0
					},
					{
						text: '单独设置折扣',
						value: 1
					},
				],
				userGradeList: [],
				deliveryList: [],
			}
		},
		onLoad({
			goods_id
		}) {
			if (goods_id) {
				this.goods_id = goods_id;
				uni.api.goodsDetail({
					goods_id
				}).then(res => {
					res.goodsInfo.goods_images?.forEach(d => {
						d.url = d.external_url;
						d.name = d.file_name;
					})
					// 设置默认值
					res.goodsInfo.is_points_gift = res.goodsInfo.is_points_gift == 0 ? 0 : 1;
					res.goodsInfo.is_points_discount = res.goodsInfo.is_points_discount == 0 ? 0 : 1;
					res.goodsInfo.is_enable_grade = res.goodsInfo.is_enable_grade == 0 ? 0 : 1;
					res.goodsInfo.is_alone_grade = res.goodsInfo.is_alone_grade == 1 ? 1 : 0;
					res.goodsInfo.specList = res.goodsInfo.specList || [];

					this.goodsInfo = res.goodsInfo;
					// 单规格逻辑
					if (this.goodsInfo.spec_type == 10) {
						this.goodsInfo.goods_price = res.goodsInfo.skuList[0].goods_price;
						this.goodsInfo.line_price = res.goodsInfo.skuList[0].line_price;
						this.goodsInfo.stock_num = res.goodsInfo.skuList[0].stock_num;
						this.goodsInfo.goods_weight = res.goodsInfo.skuList[0].goods_weight;
						console.log(this.goodsInfo)
					}
					this.fetchOptions();
					this.renderSkuList();
				})
			} else {
				// 设置默认值
				this.goodsInfo = {
					is_points_gift: 1,
					is_points_discount: 1,
					is_enable_grade: 1,
					is_alone_grade: 0,
					specList: [],
					alone_grade_equity: [],
					status: 10,
					spec_type: 10,
					skuList: [],
					deduct_stock_type: 10,
					serviceIds: [10001, 10002],
					goods_images: [],
					is_restrict: 0,
					delivery_id: 10001,
				};

				this.fetchOptions();
			}
		},
		methods: {
			// 获取其他配置
			fetchOptions() {
				uni.api.getGoodsCategory().then(res => {
					this.category = (res.list || []).map(d => ({
						text: d.name,
						value: d.category_id
					}));
				})
				uni.api.serviceList().then(res => {
					this.serviceList = (res.list || []).map(d => ({
						text: d.name,
						value: d.service_id
					}));
				})
				uni.api.userGradeList().then(res => {
					this.userGradeList = res.list || [];
					// 设置会员折扣数值
					if (!this.goodsInfo.alone_grade_equity.length) {
						this.userGradeList.forEach(dd => {
							this.goodsInfo.alone_grade_equity[`${dd.grade_id}`] = dd.equity.discount;
						})
					}
				})
				uni.api.deliveryList().then(res => {
					this.deliveryList = (res.list || []).map(d => ({
						text: d.name,
						value: d.delivery_id
					}));
				})
			},
			// 生成SKU 列表
			renderSkuList() {
				const specGroupArr = this.specGroupArr(this.goodsInfo.specList);
				const cartesianList = cartesianProductOf(specGroupArr);
				const skuList = this.goodsInfo.skuList;
				this.cartesianList = cartesianList.map((dd, ii) => {
					if (skuList?.[ii]?.image) {
						skuList[ii].image.url = skuList[ii].image.external_url;
						skuList[ii].image.name = skuList[ii].image.name;
					}
					return {
						...skuList[ii],
						image: skuList[ii]?.image ? [skuList[ii].image] : [],
						list: dd
					}
				});
			},
			// 整理所有的规格
			specGroupArr(specList = []) {
				const specGroupArr = []
				specList.forEach(specGroup => {
					const itemArr = []
					specGroup.valueList.forEach(value => {
						itemArr.push(value)
					})
					specGroupArr.push(itemArr)
				})
				console.log(specGroupArr)
				return specGroupArr
			},
			// 选择图上传
			selectUpload(e) {
				const token = uni.getStorageSync(storageKey.token) || null;
				const tempFiles = e.tempFiles;
				tempFiles.forEach(d => {
					uni.showLoading({
						title: '加载中'
					})
					uni.uploadFile({
						url: `${appConfig.host}/store/upload/image`,
						name: 'iFile',
						header: {
							'Access-Token': token
						},
						filePath: d.path,
						formData: {
							groupId: 0
						},
						success: (res) => {
							const {
								data
							} = JSON.parse(res.data); 
							if (JSON.parse(res.data).status == 200) {
								
								data.fileInfo.file_id = data.fileInfo.file_id
								data.fileInfo.url = data.fileInfo.external_url;
								data.fileInfo.name = data.fileInfo.file_name;
								this.goodsInfo.goods_images = [
									...this.goodsInfo.goods_images,
									data.fileInfo
								]
							}else{
								uni.showToast({
									title: JSON.parse(res.data).message,
									icon: 'error',
									duration: 2000 // 提示框的显示时间，单位毫秒，默认1500  
								});
							}
						},
						complete: () => {
							uni.hideLoading();
						}
					})
				})
			},
			// 删除上传图片
			onRemoveUpload(e) {
				this.goodsInfo.goods_images.splice(e.index,1);
			},
			// 添加商品规格
			onAddSpecList() {
				const specList = this.goodsInfo.specList || [];
				if (specList.length < 3) {
					this.goodsInfo.specList.push({
						key: specList.length || 0,
						spec_name: '',
						valueList: []
					});
				}
				this.renderSkuList();
			},
			// 添加规格值
			onAddValueList(specIndex) {
				if (!this.goodsInfo.specList[specIndex].valueList) {
					this.goodsInfo.specList[specIndex].valueList = [];
				}
				const specGroupItem = this.goodsInfo.specList[specIndex]
				const specValueList = specGroupItem.valueList
				this.goodsInfo.specList[specIndex].valueList.push({
					key: specValueList.length || 0,
					groupKey: specGroupItem.key,
					spec_value: ''
				});
				this.renderSkuList();
			},
			// 删除商品规格
			onRemoveSpecList(index) {
				this.goodsInfo.specList.splice(index, 1);
				this.renderSkuList();
			},
			// 删除规格值
			onRemoveValueList(specIndex, valueIndex) {
				this.goodsInfo.specList[specIndex].valueList.splice(valueIndex, 1);
				this.renderSkuList();
			},
			// SKU选择图上传
			selectSKUUpload(e, index) {
				const token = uni.getStorageSync(storageKey.token) || null;
				const tempFiles = e.tempFiles;
				tempFiles.forEach(d => {
					uni.showLoading({
						title: '加载中'
					})
					uni.uploadFile({
						url: `${appConfig.host}/store/upload/image`,
						name: 'iFile',
						header: {
							'Access-Token': token
						},
						filePath: d.path,
						formData: {
							groupId: 0
						},
						success: (res) => {
							const {
								data
							} = JSON.parse(res.data);
							if (data) {
								data.fileInfo.url = data.fileInfo.external_url;
								data.fileInfo.name = data.fileInfo.file_name;
								this.cartesianList[index].image_id = data.fileInfo.file_id;
								this.cartesianList[index].image = data.fileInfo;
							}
						},
						complete: () => {
							uni.hideLoading();
						}
					})
				})
			},
			// SKU删除上传图片
			onRemoveSKUUpload(e, index) {
				this.cartesianList[index].image = null;
				this.cartesianList[index].image_id = null;
			},

			// 生成skuList
			buildSkuList(cartesianList) {
				// 生成新的skuList
				const newSkuList = []
				for (let i = 0; i < cartesianList.length; i++) {

					console.log(cartesianList[i])

					const newSkuItem = {
						...cartesianList[i],
						key: i,
						tempId: cartesianList[i].list.map(item => item.spec_value).join('_'),
						// skuKeys用于传参给后端
						skuKeys: cartesianList[i].list.map(item => {
							return {
								groupKey: item.groupKey,
								valueKey: item.key
							}
						})
					}
					cartesianList[i].list.forEach((val, idx) => {
						newSkuItem[`spec_value_${idx}`] = val.spec_value
					})
					newSkuList.push(newSkuItem)
				}
				return newSkuList
			},


			//保存
			handleKeep() {
				const goodsInfo = this.goodsInfo;
				console.log(goodsInfo)
				console.log(this.cartesianList)
				console.log(this.buildSkuList(this.cartesianList))

				const alone_grade_equity = {};
				for (var key in goodsInfo.alone_grade_equity) {
					alone_grade_equity[`grade_id:${key}`] = goodsInfo.alone_grade_equity[key];
				}

				const formData = {
					...goodsInfo,
					alone_grade_equity,
					imagesIds: goodsInfo.goods_images.map(d => d.file_id) || [],
					specData: {
						specList: goodsInfo.specList,
						skuList: this.buildSkuList(this.cartesianList)
					}
				}
				if (this.goods_id) {
					uni.api.updateGoods({
						form: formData,
						goodsId: this.goods_id
					}).then(res => {
						if (!res.err) {
							uni.showToast({
								title: '编辑成功',
								icon: 'success',
								duration: 2000 // 提示框的显示时间，单位毫秒，默认1500  
							});
							/* setTimeout(() => {
								// 跳转到目标页面  
								//页面跳转到订单列表
								window.location.href = '/storeadmin/#/?tabbar=product';
							}, 1000); */
						}
					})

				} else {
					uni.api.createGoods({
						form: formData,
					}).then(res => {
						console.log(22,res)
						if (!res.err) {
							uni.showToast({
								title: '添加成功',
								icon: 'success',
								duration: 2000 // 提示框的显示时间，单位毫秒，默认1500  
							});
							setTimeout(() => {
								// 跳转到目标页面  
								//页面跳转到订单列表
								window.location.href = '/storeadmin/#/?tabbar=product';
							}, 1000);
						}
						
					})
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	.form-list {
		padding: 30rpx;
		padding-bottom: 100rpx;
		box-sizing: border-box;

		.cont-one {
			background-color: #eee;
			border-radius: 10rpx;
			padding: 20rpx;
			box-sizing: border-box;
			margin-bottom: 20rpx;

			.sku-name {
				margin-bottom: 20rpx;
			}

			.form-label {
				margin-bottom: 15rpx;
			}

			.form-content {
				margin-bottom: 30rpx;
				display: flex;
				align-items: center;

				.common-input {
					width: 100%;
					border: 1rpx solid #ddd;
					padding: 10rpx;
					border-radius: 10rpx;
					background-color: #fff;
				}

				.delete-icon {
					margin-left: 20rpx;
				}
			}
		}
	}

	.keep-button {
		width: 300px;
		height: 70rpx;
		background-color: red;
		color: #fff;
		border-radius: 35rpx;
		font-size: 35rpx;
		font-weight: bold;
		display: flex;
		justify-content: center;
		align-items: center;
		position: fixed;
		left: 50%;
		bottom: 60rpx;
		transform: translate(-50%, 0);
	}

	.add-btn {
		padding: 5rpx 20rpx;
		min-width: 150rpx;
		text-align: center;
		margin-right: 10rpx;
		border: 1px solid #999;
		border-radius: 5rpx;
	}

	.specList {
		margin-bottom: 4px;
	}

	.valueList,
	.sku-items,
	.specList {
		padding: 8rpx;
		border: 1px solid #999;
	}

	.sku-list {
		.sku-items {
			margin-bottom: 8rpx;
		}

		.form-items {
			display: flex;

			&>view {
				flex: 1;

				&:first-child {
					margin-right: 4rpx;
				}

				&:last-child {
					margin-left: 4rpx;
				}
			}
		}
	}
</style>